﻿using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Filters;
using Microsoft.Extensions.DependencyInjection;

namespace Luka;

/// <summary>
/// 过滤器扩展
/// </summary>
[NotScanned]
internal static class FilterExtensions
{
    /// <summary>
    /// 是否使用过滤器
    /// </summary>
    /// <returns></returns>
    public static bool HasFilter<TFilter>(this FilterContext context) where TFilter : IFilterMetadata
    {
        return context.Filters.Any(it => it.GetType().Equals(typeof(TFilter)));
    }

    /// <summary>
    /// 注册 Mvc 过滤器
    /// </summary>
    /// <returns></returns>
    public static IMvcBuilder AddMvcFilter<TFilter>(this IMvcBuilder mvcBuilder) where TFilter : IFilterMetadata
    {
        mvcBuilder.Services.AddFilter<TFilter>();
        return mvcBuilder;
    }

    /// <summary>
    /// 添加自定义过滤器
    /// </summary>
    /// <returns></returns>
    public static IServiceCollection AddFilter<TFilter>(this IServiceCollection services) where TFilter : IFilterMetadata
    {
        services.Configure<MvcOptions>(options =>
        {
            options.Filters.Add<TFilter>();
        });
        return services;
    }
}